<?php
/**
 * 指标管理
 * 张名尊 20140503
 */
class targetModel extends RelationModel {

    protected $_auto = array(
     array('createTime','time',1,'function'),
     array('date','dateMoth',1,'callback'),
     array('createUserId','getAdminId',1,'function'),
    );
    
    protected function dateMoth(){
        return date('Y-m');
    }

    //发起关联，给后台使用，前台API 不需要使用这个
    protected $_link = array(
        'user'=>array(
            'mapping_type' => BELONGS_TO,
            'foreign_key' => 'userId',
            'class_name'   =>'admin',
            'as_fields'=>'realName',      
        ),    
        'store' => array(
            'mapping_type' => BELONGS_TO,
            'foreign_key' => 'to',
            'mapping_fields'=>'name',
            //'as_fields'=>'name',
        ),
        'region'=>array(
            'mapping_type' => BELONGS_TO,
            'foreign_key' => 'to',
            'class_name'   =>'region',
            'mapping_fields'=>'name',     
        ),  
    
              
    );    
	
	/**
	 * 导入地市指标
	 */
	public function importCityTarget($res){
		$user = getUserSession();
		$city = D('region')->getRegionNameAndId();

		foreach ($res as $row){
			if(isset($city[$row['地市']])){
				$temp = array();
				$map  = array();
				$temp['to']	 = $city[$row['地市']];	//指标发布对象
				$temp['type'] = 'city';  //类型 city : 城市；microArea: 片区; pepole ： 人员
				$temp['allModel'] = $row['总任务量'];	
				$temp['importModel'] = $row['重点机型任务量'];	
				$temp['addTime'] = time();	
				$temp['addUserId'] = $user['id'];
				$temp['month'] = date('Y-m');

				$map['to'] = $temp['to'];
				$map['month'] = $temp['month'];

				$target = D('target')->where($map)->find();
				
				if($target){
					D('target')->where($map)->save($temp);
				}else{
					D('target')->add($temp);
				}
			}
		}
	}
	
	/**
	 * 导入县区指标
	 */
	public function importMicroAreaTarget($res){
		$user = getUserSession();
		
		$region = D('region')->getRegionNameAndId($user['regionId']);

		foreach ($res as $row){
			if(isset($region[$row['县区']])){
				$temp = array();
				$map  = array();
				$temp['to']	 = $region[$row['县区']];	//指标发布对象
				$temp['type'] = 'microArea';  //类型 city : 城市；microArea: 片区; pepole ： 人员
				$temp['allModel'] = $row['总任务量'];	
				$temp['importModel'] = $row['重点机型任务量'];	
				$temp['addTime'] = time();	
				$temp['addUserId'] = $user['id'];
				$temp['month'] = date('Y-m');

				$map['to'] = $temp['to'];
				$map['month'] = $temp['month'];

				$target = D('target')->where($map)->find();
				
				if($target){
					D('target')->where($map)->save($temp);
				}else{
					D('target')->add($temp);
				}
			}
		}
	}
	
	
	/**
	 * 导入厅店指标
	 */
	public function importStoreTarget($res){
		$user = getUserSession();
		
		$map['u.roleId'] = 7;
		
		if($user['roleId'] != 1){
			$map['u.regionId'] = $user['regionId'];
		}
		
		$store = D('store')->field("s.name AS storeName, u.userName, u.id AS userId")->alias('s')
				->join(C('DB_PREFIX')."admin AS u ON u.storeId = s.id")
				->where($map)->select();
		$saler = array();
		foreach ($store as $s){
			$saler[$s['storeName']][$s['userName']] = $s['userId'];
		}

		foreach ($res as $row){
			if(isset($saler[$row['厅店']][$row['促销员']])){
				$temp = array();
				$map  = array();
				$temp['to']	 = $saler[$row['厅店']][$row['促销员']];	//指标发布对象
				$temp['type'] = 'people';  //类型 city : 城市；microArea: 片区; pepole ： 人员
				$temp['allModel'] = $row['总任务量'];	
				$temp['importModel'] = $row['重点机型任务量'];	
				$temp['addTime'] = time();	
				$temp['addUserId'] = $user['id'];
				$temp['month'] = date('Y-m');

				$map['to'] = $temp['to'];
				$map['month'] = $temp['month'];

				$target = D('target')->where($map)->find();
				
				if($target){
					D('target')->where($map)->save($temp);
				}else{
					D('target')->add($temp);
				}
			}
		}
	}
	
	/**
	 * 获得地市指标
	 */
	public function getCityTargets($month){
		$list  = array();
		$user  = getUserSession();
		
		$map['city.pid'] = 1;
		if($user['roleId'] != 1){
			$map['city.id'] = $user['regionId'];
		}

		$cities = D('region')->alias('city')->field('city.id AS cityId, city.name AS cityName')
				->where($map)->select();
		
		$field = array(
			'target.to',
			'target.allModel',
			'target.importModel',
			'target.month',
			'target.addTime',
		);
		$target = D('region')->alias('city')->field($field)
				->join(C('DB_PREFIX')."target AS target ON target.to = city.id")
				->where(array('city.pid'=>1, 'target.type'=>'city' , 'target.month'=>$month))->select();

		$user = D('admin')->field('id, userName, regionId')->where(array('roleId'=>3, 'status'=>1))->select();
		foreach ($cities as $city){
			$temp = array();
			foreach ($target as $row){
				if($row['to'] == $city['cityId']){
					$temp = $row;
				}
			}
			foreach ($user as $u){
				if($city['cityId'] == $u['regionId']){
					$temp['userName'] = $u['userName'];
				}
			}
			$list[] = array_merge($city, $temp);
		}
		return array('list'=>$list, 'page'=>NULL);
	}
	
	/**
	 * 获得县区指标
	 */
	public function getMicroAreaTargets($month, $page=TRUE){
		$list	= array();
		$user	= getUserSession();

		$map['region.level'] = 2;
		
		if($user['roleId'] != 1){
			$map['region.pid'] = $user['regionId'];
		}
		
		$count	= D('region')->alias('region')->where($map)->count('id');
		$pager	= new Page($count, 20);
		
		$db	= D('region')->alias('region')->field('region.id, region.name, city.name AS cityName')
				->join(C('DB_PREFIX')."region AS city ON city.id = region.pid")
				->where(array_merge($map))
				->order('region.pid');
				
		if($page){
			$db->limit($pager->firstRow.','.$pager->listRows);
		}
				
		$region	= $db->select();
		
		$map['target.type'] = 'microArea';
		$map['target.month'] = $month;
		
		$field	= array(
			'target.to',
			'target.allModel',
			'target.importModel',
			'target.month',
			'target.addTime',
		);
		$dudao  = D('admin')->field('id, userName, regionId')->where(array('roleId'=>4, 'status'=>1))->select();
		$target = D('region')->alias('region')->field($field)
			->join(C('DB_PREFIX')."target AS target ON target.to = region.id")
			->where($map)->select();

		foreach ($region as $r){
			$temp = array();
			foreach ($target as $row){
				if($row['to'] == $r['id']){
					$temp = $row;
				}
			}
			foreach ($dudao as $du){
				if($r['id'] == $du['regionId']){
					$temp['userName'] = $du['userName'];
				}
			}
			$list[] = array_merge($r, $temp);
		}

		return array('list'=>$list, 'page'=>$pager->show());
	}
	
	/**
	 * 获得个人指标
	 */
	public function getPepoleTargets($month, $page=TRUE){
		$list	= array();
		$user	= getUserSession();

		$map['u.roleId'] = 7;
		$map['u.status'] = 1;
		
		if($user['roleId'] == 3){
			$map['r.pid'] = $user['regionId'];
		}elseif($user['roleId'] == 4){
			$map['u.regionId'] = $user['regionId'];
		}elseif($user['roleId'] == 7){
			$map['u.id'] = $user['id'];
		}
		
		$count	= D('admin')->alias('u')
				->join(C('DB_PREFIX')."store AS s ON s.id = u.storeId")
				->join(C('DB_PREFIX')."region AS r ON r.id = s.regionId")
				->where($map)->count('u.id');
		$pager	= new Page($count, 20);
		$field	= array(
			'target.to',
			'target.allModel',
			'target.importModel',
			'target.month',
			'target.addTime',
		);
		
		$db	= D('admin')->alias('u')->field('u.id, u.userName, s.name AS storeName, s.regionId')
				->join(C('DB_PREFIX')."store AS s ON s.id = u.storeId")
				->join(C('DB_PREFIX')."region AS r ON r.id = s.regionId")
				->where($map)->order('s.regionId, s.id');
		if($page){
			$db->limit($pager->firstRow.','.$pager->listRows);
		}
				
		$res = $db->select();
				
		$map['target.type'] = 'people';
		$map['target.month'] = $month;
		
		$dudao  = D('admin')->field('id, userName, regionId')->where(array('roleId'=>4, 'status'=>1))->select();
	
		$target = D('admin')->alias('u')->field($field)
			->join(C('DB_PREFIX')."store AS s ON s.id = u.storeId")
			->join(C('DB_PREFIX')."region AS r ON r.id = s.regionId")
			->join(C('DB_PREFIX')."target AS target ON target.to = u.id")
			->where($map)->select();
		
		foreach ($res as $u){
			$temp = array();
			foreach ($target as $row){
				if($row['to'] == $u['id']){
					$temp = $row;
				}
			}
			foreach ($dudao as $du){
				if($u['regionId'] == $du['regionId']){
					$temp['dudaoName'] = $du['userName'];
				}
			}
			$list[] = array_merge($u, $temp);
		}

		return array('list'=>$list, 'page'=>$pager->show());
	}
	
}
